package com.apimarket.config;

import lombok.Data;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/16 20:41
 * @Version 1.0
 */

//@Data
//@Configuration
//@MapperScan(basePackages = SlaveDataBaseConfig.PACKAGE,sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class AtomikosSlaveDBConfig {
    /**
     * dao层的包路径
     */
    static final String PACKAGE="com.apimarket.slaveDao";
    /**
     * mapper文件的相对路径
     */
    private static final String MAPPER_LOCATION="classpath*:mapper/slave/*.xml";

    @Bean("atomikosSlaveDataSourcProperties")
    @ConfigurationProperties(prefix="spring.datasource.druid.atomikos.slave")
    public Properties slaverDataSourceProperties(){
        return new Properties();
    }

    @Bean(name="atomikosSlaveDataSource")
    @DependsOn({"xaTransaction"})
    public DataSource slaveDataSource(@Qualifier("atomikosSlaveDataSourcProperties")Properties dataSourceProperties){

        AtomikosDataSourceBean ds=new AtomikosDataSourceBean();
        //ds.setXaDataSource(mysqlXADataSource);
        ds.setUniqueResourceName("atomikosSlaveDataSource");
        //ds.setXaDataSourceClassName("org.postgresql.xa.PGXADataSource");
        ds.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
        ds.setXaProperties(dataSourceProperties);
        ds.setPoolSize(10);
        return ds;
    }

    //创建Mybatis的连接会话工厂实例
    @Bean(name = "atomikosSlaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("atomikosSlaveDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);  // 设置数据源bean
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(AtomikosSlaveDBConfig.MAPPER_LOCATION));  // 设置mapper文件路径

        return sessionFactory.getObject();
    }
}
